import turtle
import time
import random

turtle.setup(width=500, height=500)

while True:
    pos = turtle.position()
    head = turtle.heading()

    if pos[0] < -200:
        if 180 < head < 270:
            turtle.setheading(random.randint(90, 180))
        elif 270 < head < 359:
            turtle.setheading(random.randint(0, 90))
        else:
            pass

    if pos[0] > 200:
        if 0 < head < 90:
            turtle.setheading(random.randint(270, 359))
        elif 90 < head < 180:
            turtle.setheading(random.randint(180, 270))
        else:
            pass

    if pos[1] < -200:
        if 180 < head < 270:
            turtle.setheading(random.randint(270, 359))
        elif 90 < head < 180:
            turtle.setheading(random.randint(0, 90))
        else:
            pass

    if pos[1] > 200:
        if 270 < head < 359:
            turtle.setheading(random.randint(270, 180))
        elif 0 < head < 90:
            turtle.setheading(random.randint(90, 180))

    turtle.forward(10)
